package com.swy.controller;

import com.swy.model.SensitiveWord;
import com.swy.service.SensitiveWordService;
import com.swy.config.SecurityConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpStatus;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Arrays;
import com.swy.model.ImportResult;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;

@Controller
@RequestMapping("/detector/admin")
@RequiredArgsConstructor
public class SensitiveWordController {
    
    private final SensitiveWordService sensitiveWordService;
    private final SecurityConfig securityConfig;
    private static final Logger log = LoggerFactory.getLogger(SensitiveWordController.class);
    
    @GetMapping("/words")
    public String wordsPage() {
        return "words";
    }
    
    @GetMapping("/words/listData")
    @ResponseBody
    public Map<String, Object> getWords(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search) {
        
        List<SensitiveWord> words = sensitiveWordService.searchSensitiveWords(search, page, size);
        int total = sensitiveWordService.countSensitiveWords(search);
        
        Map<String, Object> result = new HashMap<>();
        result.put("content", words);
        result.put("totalPages", (total + size - 1) / size);
        result.put("totalElements", total);
        return result;
    }
    
    @PostMapping("/words")
    @ResponseBody
    public String addWord(@RequestParam String word) {
        try {
            sensitiveWordService.addSensitiveWord(word);
            return "success";
        } catch (IllegalArgumentException e) {
            return e.getMessage();
        }
    }
    
    @DeleteMapping("/words")
    @ResponseBody
    public String deleteWord(@RequestParam String word) {
        sensitiveWordService.deleteSensitiveWord(word);
        return "success";
    }
    
    @GetMapping("/words/export")
    public ResponseEntity<byte[]> exportWords() {
        try {
            // 获取所有敏感词
            List<SensitiveWord> words = sensitiveWordService.getAllSensitiveWords();
            
            // 将敏感词列表转换为文本，每个词一行，换行符适配操作系统
            String content = words.stream()
                    .map(SensitiveWord::getWord)
                    .collect(Collectors.joining(System.lineSeparator()));
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            headers.setContentDispositionFormData("attachment", "sensitive-words.txt");
            
            // 返回文件内容
            return new ResponseEntity<>(content.getBytes(StandardCharsets.UTF_8), headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出敏感词失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    @PostMapping("/cache/clean")
    @ResponseBody
    public String cleanCache() {
        try {
            // 获取项目根目录
            String userDir = System.getProperty("user.dir");
            Path uploadsPath = Paths.get(userDir, "uploads");
            
            // 检查目录是否存在
            if (!Files.exists(uploadsPath)) {
                log.warn("uploads目录不存在: {}", uploadsPath);
                return "uploads目录不存在";
            }
            
            // 获取目录中的所有文件
            List<Path> files = Files.list(uploadsPath)
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
            
            if (files.isEmpty()) {
                log.info("uploads目录为空，无需清理");
                return "success";
            }
            
            // 删除所有文件
            int deletedCount = 0;
            for (Path file : files) {
                try {
                    Files.delete(file);
                    deletedCount++;
                    log.info("已删除文件: {}", file.getFileName());
                } catch (IOException e) {
                    log.error("删除文件失败: {}", file.getFileName(), e);
                }
            }
            
            log.info("缓存清理完成，共删除 {} 个文件", deletedCount);
            return "success";
            
        } catch (IOException e) {
            log.error("清理缓存时发生错误", e);
            return "清理失败: " + e.getMessage();
        }
    }

    @PostMapping("/account/update")
    @ResponseBody
    public String updateAccount(@RequestParam String username, @RequestParam String password) {
        try {
            // 更新配置文件
            String userDir = System.getProperty("user.dir");
            Path configPath = Paths.get(userDir, "author/config.properties");
            Properties props = new Properties();
            
            // 读取现有配置
            try (FileInputStream fis = new FileInputStream(configPath.toFile())) {
                props.load(fis);
            }
            
            // 更新配置
            props.setProperty("username", username);
            props.setProperty("password", password);
            
            // 保存配置
            try (FileOutputStream fos = new FileOutputStream(configPath.toFile())) {
                props.store(fos, "Updated by admin");
            }
            
            // 重新加载用户配置
            securityConfig.reloadUsers();
            
            log.info("账户信息已更新: {}", username);
            return "success";
        } catch (Exception e) {
            log.error("更新账户信息失败", e);
            return "更新失败: " + e.getMessage();
        }
    }

    // 批量删除敏感词
    @PostMapping("/words/batchDelete")
    @ResponseBody
    public String batchDeleteWords(@RequestBody List<String> words) {
        try {
            sensitiveWordService.deleteSensitiveWords(words);
            return "success";
        } catch (Exception e) {
            log.error("批量删除敏感词失败", e);
            return "批量删除失败: " + e.getMessage();
        }
    }

    @PostMapping("/words/import")
    public ResponseEntity<?> importWords(@RequestParam("file") MultipartFile file) {
        log.info("接收到文件上传请求 - 文件名: {}, 大小: {} bytes", file.getOriginalFilename(), file.getSize());
        
        if (file.isEmpty()) {
            log.warn("上传的文件为空");
            Map<String, String> response = new HashMap<>();
            response.put("error", "上传的文件为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 检查文件格式
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".txt")) {
            log.warn("不支持的文件格式: {}", originalFilename);
            Map<String, String> response = new HashMap<>();
            response.put("error", "只支持TXT格式的文件");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 检查文件编码
            byte[] bytes = file.getBytes();
            String content = new String(bytes, StandardCharsets.UTF_8);
            
            // 尝试用UTF-8重新编码，如果结果不同则说明不是UTF-8编码
            String reEncoded = new String(bytes, StandardCharsets.UTF_8);
            if (!content.equals(reEncoded)) {
                log.warn("文件编码不是UTF-8");
                Map<String, String> response = new HashMap<>();
                response.put("error", "文件必须是UTF-8编码");
                return ResponseEntity.badRequest().body(response);
            }

            // 按行分割
            String[] words = content.split("\\r?\\n");
            log.info("从文件中解析出 {} 个词", words.length);
            
            // 调用服务进行导入
            ImportResult result = sensitiveWordService.importSensitiveWords(Arrays.asList(words));
            log.info("导入完成 - 结果: {}", result);
            
            Map<String, Object> response = new HashMap<>();
            response.put("addedCount", result.getAddedCount());
            response.put("duplicateCount", result.getDuplicateCount());
            response.put("duplicateWords", result.getDuplicateWords());
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            log.error("处理上传文件时发生错误", e);
            Map<String, String> response = new HashMap<>();
            response.put("error", "处理文件时发生错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
} 